package com.xiehua.task.server;

import com.xiehua.task.job.bucket.CronBucket;
import com.xiehua.task.job.bucket.TopicBucket;
import com.xiehua.task.redis.RedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.utils.json.Json;
import org.tio.server.intf.ServerAioListener;

/**
 * @author tanyaowu
 * 2017年3月26日 下午8:22:31
 */
public class ServerListener implements ServerAioListener {

	private static Logger log = LoggerFactory.getLogger(ServerListener.class);

	/**
	 *
	 * @author tanyaowu
	 */
	public ServerListener() {
	}

	/**
	 * @param channelContext
	 * @param throwable
	 * @param remark
	 * @param isRemove
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
		log.info("客户端断开连接:{},是否移除:{}",throwable,isRemove);
		if(isRemove && throwable != null){
			CronBucket cronBucket = new CronBucket(RedisTemplate.getJedis());
			cronBucket.delCron(channelContext.getClientNode(),channelContext.getGroupContext());
			cronBucket.clear();

			TopicBucket topicBucket = new TopicBucket(RedisTemplate.getJedis());
			topicBucket.delTopicInfo(channelContext.getClientNode(),channelContext.getGroupContext());
			topicBucket.clear();
		}
	}

	/**
	 * @param channelContext
	 * @param isConnected
	 * @param isReconnect
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
		log.info("客户端连接成功");
	}

	/**
	 * @param channelContext
	 * @param packet
	 * @param packetSize
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterReceived(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {
		log.info("onAfterReceived channelContext:{}, packet:{}, packetSize:{}", channelContext, Json.toJson(packet), packetSize);
	}

	/**
	 * @param channelContext
	 * @param packet
	 * @param isSentSuccess
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
		log.info("onAfterSent channelContext:{}, packet:{}, isSentSuccess:{}", channelContext, Json.toJson(packet), isSentSuccess);
	}

	@Override
	public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) {
	}
}
